
<template>
  <div class="search-view">
    <div class="header">
      <h1>搜索结果</h1>
      <p v-if="!loading">找到 {{ total }} 个与 "<strong>{{ query }}</strong>" 相关的商品</p>
    </div>

    <div v-if="loading" class="loading-spinner">
      <LoadingSpinner />
    </div>

    <div v-else-if="products.length > 0" class="product-grid">
      <ProductCard v-for="product in products" :key="product.id" :product="product" />
    </div>

    <div v-else>
      <EmptyState 
        title="未找到商品"
        :description="`抱歉，没有找到与 '${query}' 相关的商品。`"
      />
    </div>

    <el-pagination
      v-if="products.length > 0"
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
      class="pagination"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { searchProducts } from '@/api/modules/product'
import type { Product } from '@/types'
import ProductCard from '@/components/business/ProductCard.vue'
import LoadingSpinner from '@/components/base/LoadingSpinner.vue'
import EmptyState from '@/components/base/EmptyState.vue'

const route = useRoute()
const products = ref<Product[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(12)
const loading = ref(false)
const query = ref(route.query.q as string)

const performSearch = async () => {
  if (!query.value) return

  try {
    loading.value = true
    const response = await searchProducts({
      keyword: query.value,
      page: page.value,
      size: pageSize.value,
    })
    products.value = response.products
    total.value = response.total
  } catch (error) {
    ElMessage.error('搜索商品失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (currentPage: number) => {
  page.value = currentPage
  performSearch()
}

watch(() => route.query.q, (newQuery) => {
  query.value = newQuery as string
  page.value = 1
  performSearch()
})

onMounted(() => {
  performSearch()
})
</script>

<style scoped>
.search-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.loading-spinner {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style>
